package com.hc.security;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.utils.GlobalConstant;
import com.hc.utils.JsonUtil;
import com.hc.utils.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功(登录成功)处理器处理
 *
 * @author 梁云亮
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    JwtUtils jwtUtils;

    /**
     * 登录成功之后，将token信息放在res中返回
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        response.setContentType("application/json;charset=UTF-8");

        ServletOutputStream outputStream = response.getOutputStream();
        // 生成jwt返回
        String token = jwtUtils.createToken(authentication.getName());

        //将token放在res中返回
        Result result = ResultUtil.success(200, "登录成功", token);
        outputStream.write(JsonUtil.obj2String(result).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}